<?php
/**
 * Created by PhpStorm.
 * User: micoya
 * Date: 2018/11/8
 * Time: 12:14 AM
 */

namespace app\index\controller;


use app\common\base\Form;
use app\common\model\Admin;
use app\common\model\User;
use think\Controller;
use think\Db;
use think\Error;
use think\Session;

class AuthController extends Controller {

    public function Register() {
        Form::Validate([
            'username' => 'require',
            'password' => 'require',
        ]);

        // 获取数据
        $username = input('username');
        $password = input('password');

        // 对密码做编码
        $password = md5($password);

        // 获取用户
        $user = User::GetByUsername($username);
        if ($user) {
            return Error('用户名已存在');
        }

        $result = Db::table('user')->insert([
            'username'  =>  $username,
            'password'  =>  $password,
        ]);

        if (!$result) {
            return Error('注册失败');
        }

        return Success('注册成功');

    }

    // 登录
    public function Login() {

        Form::Validate([
            'username' => 'require',
            'password' => 'require',
        ]);

        // 获取数据
        $username = input('username');
        $password = input('password');

        // 对密码做编码
        $password = md5($password);

        // 获取用户
        $user = User::GetByUsername($username);
        if (!$user || $user['password'] !== $password) {
            return Error('用户名或密码错误');
        }
        // 去掉密码字段
        unset($user['password']);

        // 设置Session
        Session::set('user', $user);

        return Success('登录成功');
    }

    // 登出
    public function Logout() {

        Session::delete('user');

        return Success('登出成功');

    }

    // 查询登录状态
    public function LoginStatus() {

        if (Session::has('user')) {
            return Success('', Session::get('user'));
        } else {
            return Error();
        }

    }

}